"""
业务级自动断言系统 - 基于record_id的业务测试断言
支持CRUD操作的智能断言和业务流程验证
"""

import json
import re
import pymysql
import os
from typing import Dict, List, Any, Optional, Tuple
from enum import Enum
import logging
from datetime import datetime
import traceback
import sys
from pathlib import Path

# 将项目根目录添加到 Python 路径
sys.path.append(str(Path(__file__).parent.parent.parent))
from config.config import settings

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class AssertionType(Enum):
    """断言类型枚举"""
    STATUS_CODE = "status_code"
    RESPONSE_TIME = "response_time"
    DATA_CONSISTENCY = "data_consistency"
    ERROR_MESSAGE = "error_message"


class AssertionResult:
    """断言结果类"""
    def __init__(self, success: bool, message: str, assertion_type: AssertionType,
                 expected: Any = None, actual: Any = None, description: str = None):
        self.success = success
        self.message = message
        self.assertion_type = assertion_type
        self.expected = expected
        self.actual = actual
        self.description = description

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "success": self.success,
            "message": self.message,
            "type": self.assertion_type.value,
            "expected": self.expected,
            "actual": self.actual,
            "description": self.description
        }


class StatusCodeAssertion:
    """智能状态码断言"""
    
    def assert_condition(self, test_data: Dict[str, Any], test_result: Dict[str, Any]) -> AssertionResult:
        """执行状态码断言"""
        # 从test_data中提取信息
        data_type = test_data.get("data_type")
        operation_type = test_data.get("operation_type")
        
        # 解析test_data JSON
        test_data_json = test_data.get("test_data", {})
        if isinstance(test_data_json, str):
            test_data_json = json.loads(test_data_json)
        
        # 提取预期结果和描述
        expected_result = test_data_json.get("expected_result", "")
        case_name = test_data_json.get("case_name", "")
        description = test_data_json.get("description", "")
        
        # 从test_result中提取信息
        success = test_result.get("success", False)
        response_data = test_result.get("response_data")
        error_message = test_result.get("error_message")
        
        # 解析响应数据
        if response_data and isinstance(response_data, str):
            response_data = json.loads(response_data)
        
        # 智能判断预期状态
        expected_success, reason = self._determine_expected_status(
            data_type, expected_result, case_name, operation_type
        )
        
        # 获取实际状态码
        actual_code = None
        if response_data and isinstance(response_data, dict):
            actual_code = response_data.get("code")
        
        # 判断实际是否成功
        actual_success = success and str(actual_code) == "0"
        
        # 生成断言描述
        assertion_desc = f"验证 {case_name or operation_type} 的执行结果"
        if description:
            assertion_desc += f" - {description}"
        
        # 比较预期和实际
        if expected_success == actual_success:
            return AssertionResult(
                success=True,
                message=f"状态断言通过：预期{'成功' if expected_success else '失败'}，"
                       f"实际{'成功' if actual_success else '失败'} ({reason})",
                assertion_type=AssertionType.STATUS_CODE,
                expected={"success": expected_success, "code": "0" if expected_success else "非0"},
                actual={"success": actual_success, "code": actual_code},
                description=assertion_desc
            )
        else:
            return AssertionResult(
                success=False,
                message=f"状态断言失败：预期{'成功' if expected_success else '失败'}，"
                       f"但实际{'成功' if actual_success else '失败'} ({reason})",
                assertion_type=AssertionType.STATUS_CODE,
                expected={"success": expected_success, "code": "0" if expected_success else "非0"},
                actual={"success": actual_success, "code": actual_code, "error": error_message},
                description=assertion_desc
            )
    
    def _determine_expected_status(self, data_type: str, expected_result: str, 
                                 case_name: str, operation_type: str) -> Tuple[bool, str]:
        """智能判断预期状态"""
        # 1. 首先根据data_type判断
        if data_type == "normal":
            base_expectation = True
            reason = "数据类型为normal，预期操作成功"
        elif data_type == "invalid":
            base_expectation = False
            reason = "数据类型为invalid，预期操作失败"
        else:
            base_expectation = True
            reason = "默认预期成功"
        
        # 2. 根据expected_result中的关键词进一步判断
        success_keywords = ["成功", "success", "正常", "通过", "创建成功", "更新成功", "删除成功", "查询成功"]
        failure_keywords = ["失败", "fail", "错误", "异常", "不存在", "找不到", "不合法", "重复"]
        
        expected_result_lower = expected_result.lower()
        case_name_lower = case_name.lower() if case_name else ""
        
        # 检查关键词
        has_success_keyword = any(keyword in expected_result_lower for keyword in success_keywords)
        has_failure_keyword = any(keyword in expected_result_lower for keyword in failure_keywords)
        
        # 也检查case_name中的关键词
        has_success_in_name = any(keyword in case_name_lower for keyword in success_keywords)
        has_failure_in_name = any(keyword in case_name_lower for keyword in failure_keywords)
        
        # 如果有明确的关键词，覆盖data_type的判断
        if has_failure_keyword or has_failure_in_name:
            return False, f"预期结果或用例名称包含失败关键词：{expected_result or case_name}"
        elif has_success_keyword or has_success_in_name:
            return True, f"预期结果或用例名称包含成功关键词：{expected_result or case_name}"
        
        # 3. 特殊情况：删除不存在的记录
        if operation_type == "delete" and ("不存在" in expected_result or "不存在" in case_name):
            return False, "尝试删除不存在的记录，预期失败"
        
        return base_expectation, reason


class ResponseTimeAssertion:
    """响应时间断言"""
    
    def assert_condition(self, test_data: Dict[str, Any], test_result: Dict[str, Any],
                        max_time: int = 2000) -> AssertionResult:
        """执行响应时间断言"""
        execution_time = test_result.get("execution_time", 0)
        operation_type = test_data.get("operation_type")
        
        # 解析test_data获取用例信息
        test_data_json = test_data.get("test_data", {})
        if isinstance(test_data_json, str):
            test_data_json = json.loads(test_data_json)
        
        case_name = test_data_json.get("case_name", f"{operation_type}操作")
        
        # 根据操作类型调整阈值
        thresholds = {
            "create": 2500,  # 创建操作允许更长时间
            "read": 1000,    # 读取应该较快
            "update": 1500,  # 更新操作中等
            "delete": 1500   # 删除操作中等
        }
        
        max_allowed_time = thresholds.get(operation_type, max_time)
        
        success = execution_time <= max_allowed_time
        
        return AssertionResult(
            success=success,
            message=f"响应时间{'符合' if success else '超出'}预期：{execution_time}ms "
                   f"{'<=' if success else '>'} {max_allowed_time}ms",
            assertion_type=AssertionType.RESPONSE_TIME,
            expected=f"<= {max_allowed_time}ms",
            actual=f"{execution_time}ms",
            description=f"验证 {case_name} 的响应时间"
        )


class DataConsistencyAssertion:
    """数据一致性断言"""
    
    def assert_condition(self, business_operations: List[Dict[str, Any]]) -> List[AssertionResult]:
        """验证业务流程中的数据一致性"""
        results = []
        
        # 按操作类型分组
        operations_by_type = {}
        for op in business_operations:
            op_type = op["test_data"]["operation_type"]
            if op_type not in operations_by_type:
                operations_by_type[op_type] = []
            operations_by_type[op_type].append(op)
        
        # 验证创建后的读取
        if "create" in operations_by_type and "read" in operations_by_type:
            result = self._check_create_read_consistency(
                operations_by_type["create"],
                operations_by_type["read"]
            )
            if result:
                results.append(result)
        
        # 验证更新后的读取
        if "update" in operations_by_type and "read" in operations_by_type:
            result = self._check_update_read_consistency(
                operations_by_type["update"],
                operations_by_type["read"]
            )
            if result:
                results.append(result)
        
        # 验证删除后的读取
        if "delete" in operations_by_type and "read" in operations_by_type:
            result = self._check_delete_read_consistency(
                operations_by_type["delete"],
                operations_by_type["read"]
            )
            if result:
                results.append(result)
        
        return results
    
    def _check_create_read_consistency(self, creates: List[Dict], reads: List[Dict]) -> Optional[AssertionResult]:
        """检查创建和读取的一致性"""
        # 找到成功的创建操作
        successful_create = None
        for create_op in creates:
            if create_op["test_result"]["success"]:
                successful_create = create_op
                break
        
        if not successful_create:
            return None
        
        # 找到创建后的第一个读取操作
        create_time = successful_create["test_data"]["created_at"]
        subsequent_read = None
        for read_op in reads:
            if read_op["test_data"]["created_at"] > create_time:
                subsequent_read = read_op
                break
        
        if not subsequent_read:
            return None
        
        # 检查读取是否成功并返回数据
        read_result = subsequent_read["test_result"]
        if read_result["success"] and read_result.get("response_data"):
            response_data = json.loads(read_result["response_data"])
            if response_data.get("data", {}).get("items"):
                return AssertionResult(
                    success=True,
                    message="创建后的读取操作成功返回数据",
                    assertion_type=AssertionType.DATA_CONSISTENCY,
                    description="验证创建操作后数据可以被正确读取"
                )
        
        return AssertionResult(
            success=False,
            message="创建后的读取操作未能返回预期数据",
            assertion_type=AssertionType.DATA_CONSISTENCY,
            description="验证创建操作后数据可以被正确读取"
        )
    
    def _check_update_read_consistency(self, updates: List[Dict], reads: List[Dict]) -> Optional[AssertionResult]:
        """检查更新和读取的一致性"""
        # 类似的逻辑，检查更新后的数据是否能正确读取
        return None  # 简化示例
    
    def _check_delete_read_consistency(self, deletes: List[Dict], reads: List[Dict]) -> Optional[AssertionResult]:
        """检查删除和读取的一致性"""
        # 找到成功的删除操作
        successful_delete = None
        for delete_op in deletes:
            if delete_op["test_result"]["success"]:
                successful_delete = delete_op
                break
        
        if not successful_delete:
            return None
        
        # 找到删除后的读取操作
        delete_time = successful_delete["test_data"]["created_at"]
        subsequent_read = None
        for read_op in reads:
            if read_op["test_data"]["created_at"] > delete_time:
                subsequent_read = read_op
                break
        
        if not subsequent_read:
            return None
        
        # 检查读取是否返回空数据
        read_result = subsequent_read["test_result"]
        if read_result["success"] and read_result.get("response_data"):
            response_data = json.loads(read_result["response_data"])
            items = response_data.get("data", {}).get("items", [])
            if not items:  # 删除后应该没有数据
                return AssertionResult(
                    success=True,
                    message="删除后的读取操作正确返回空数据",
                    assertion_type=AssertionType.DATA_CONSISTENCY,
                    description="验证删除操作后数据不再存在"
                )
        
        return AssertionResult(
            success=False,
            message="删除后的读取操作仍返回数据",
            assertion_type=AssertionType.DATA_CONSISTENCY,
            description="验证删除操作后数据不再存在"
        )


class ErrorMessageAssertion:
    """错误信息断言"""
    
    def assert_condition(self, test_data: Dict[str, Any], test_result: Dict[str, Any]) -> Optional[AssertionResult]:
        """验证错误信息是否符合预期"""
        # 只对失败的操作进行错误信息断言
        if test_result.get("success", False):
            return None
        
        error_message = test_result.get("error_message", "")
        if not error_message:
            return None
        
        operation_type = test_data.get("operation_type")
        
        # 解析test_data获取预期信息
        test_data_json = test_data.get("test_data", {})
        if isinstance(test_data_json, str):
            test_data_json = json.loads(test_data_json)
        
        expected_result = test_data_json.get("expected_result", "")
        case_name = test_data_json.get("case_name", "")
        
        # 解析错误信息
        error_type, error_detail = self._parse_error_message(error_message)
        
        # 验证错误类型是否符合预期
        is_expected = self._validate_error_expectation(
            error_type, error_detail, expected_result, operation_type
        )
        
        return AssertionResult(
            success=is_expected,
            message=f"错误信息{'符合' if is_expected else '不符合'}预期：{error_type}",
            assertion_type=AssertionType.ERROR_MESSAGE,
            expected=expected_result,
            actual=error_detail,
            description=f"验证 {case_name} 的错误信息"
        )
    
    def _parse_error_message(self, error_message: str) -> Tuple[str, str]:
        """解析错误信息，提取错误类型和详情"""
        # 处理删除操作的错误信息
        delete_pattern = r'"message":"([^"]+)"'
        delete_match = re.search(delete_pattern, error_message)
        if delete_match:
            return "记录不存在", delete_match.group(1)
        
        # 处理更新/创建操作的错误信息
        field_pattern = r'for field \[([^\]]+)\]'
        field_match = re.search(field_pattern, error_message)
        if field_match:
            field_name = field_match.group(1)
            return f"字段错误：{field_name}", error_message
        
        # 处理参数不合法错误
        if "请求参数不合法" in error_message:
            return "参数不合法", error_message
        
        return "未知错误", error_message
    
    def _validate_error_expectation(self, error_type: str, error_detail: str, 
                                  expected_result: str, operation_type: str) -> bool:
        """验证错误是否符合预期"""
        expected_lower = expected_result.lower()
        
        # 删除不存在的记录
        if "记录不存在" in error_type and ("不存在" in expected_lower or "找不到" in expected_lower):
            return True
        
        # 字段错误
        if "字段错误" in error_type and ("字段" in expected_lower or "参数" in expected_lower):
            return True
        
        # 参数不合法
        if "参数不合法" in error_type and ("不合法" in expected_lower or "无效" in expected_lower):
            return True
        
        # 默认：如果是失败操作且有错误信息，认为符合预期
        return True


class DatabaseManager:
    """数据库管理器"""
    
    def __init__(self, host: str, user: str, password: str, database: str, port: int = 3306):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.port = port
        self.connection = None
    
    def connect(self):
        """连接数据库"""
        try:
            self.connection = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database,
                port=self.port,
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            logger.info("数据库连接成功")
        except Exception as e:
            logger.error(f"数据库连接失败: {str(e)}")
            raise
    
    def disconnect(self):
        """断开数据库连接"""
        if self.connection:
            self.connection.close()
            logger.info("数据库连接已断开")
    
    def execute_query(self, query: str, params: tuple = None) -> List[Dict]:
        """执行查询"""
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(query, params)
                return cursor.fetchall()
        except Exception as e:
            logger.error(f"查询执行失败: {str(e)}")
            raise


class BusinessAssertionEngine:
    """业务级自动断言引擎"""
    
    def __init__(self, db_manager: DatabaseManager):
        self.db_manager = db_manager
        self.status_assertion = StatusCodeAssertion()
        self.response_time_assertion = ResponseTimeAssertion()
        self.data_consistency_assertion = DataConsistencyAssertion()
        self.error_message_assertion = ErrorMessageAssertion()
    
    def get_business_data(self, record_id: str) -> List[Dict[str, Any]]:
        """获取业务的所有测试数据和结果"""
        query = """
        SELECT 
            td.*,
            tr.id as result_id,
            tr.test_case_name as result_case_name,
            tr.success,
            tr.response_data,
            tr.error_message,
            tr.execution_time
        FROM test_data td
        LEFT JOIN test_result tr ON td.id = tr.test_data_id
        WHERE td.record_id = %s
        ORDER BY td.id
        """
        
        results = self.db_manager.execute_query(query, (record_id,))
        
        # 组织数据结构
        business_data = []
        for row in results:
            business_data.append({
                "test_data": {
                    "id": row["id"],
                    "record_id": row["record_id"],
                    "object_api_name": row["object_api_name"],
                    "data_type": row["data_type"],
                    "operation_type": row["operation_type"],
                    "test_data": row["test_data"],
                    "created_at": row["created_at"]
                },
                "test_result": {
                    "id": row["result_id"],
                    "test_case_name": row["result_case_name"],
                    "success": row["success"],
                    "response_data": row["response_data"],
                    "error_message": row["error_message"],
                    "execution_time": row["execution_time"]
                } if row["result_id"] else None
            })
        
        return business_data
    
    def execute_operation_assertions(self, test_data: Dict[str, Any], 
                                   test_result: Dict[str, Any]) -> List[AssertionResult]:
        """执行单个操作的所有断言"""
        assertions = []
        
        # 1. 状态码断言
        status_result = self.status_assertion.assert_condition(test_data, test_result)
        assertions.append(status_result)
        
        # 2. 响应时间断言
        time_result = self.response_time_assertion.assert_condition(test_data, test_result)
        assertions.append(time_result)
        
        # 3. 错误信息断言（仅对失败的操作）
        error_result = self.error_message_assertion.assert_condition(test_data, test_result)
        if error_result:
            assertions.append(error_result)
        
        return assertions
    
    def execute_business_assertions(self, record_id: str) -> Dict[str, Any]:
        """执行整个业务的断言"""
        try:
            # 获取业务数据
            business_data = self.get_business_data(record_id)
            
            if not business_data:
                return {
                    "success": False,
                    "error": f"未找到record_id为{record_id}的业务数据",
                    "record_id": record_id
                }
            
            # 执行操作级断言
            operation_results = []
            for operation in business_data:
                if operation["test_result"]:  # 确保有测试结果
                    assertions = self.execute_operation_assertions(
                        operation["test_data"],
                        operation["test_result"]
                    )
                    
                    # 提取操作描述信息
                    test_data_json = json.loads(operation["test_data"]["test_data"])
  
                    operation_results.append({
                        "operation_type": operation["test_data"]["operation_type"],
                        # "case_name": test_data_json.get("case_name", "读操作"),
                        "case_name": operation["test_result"]["test_case_name"],
                        "description": test_data_json.get("description", ""),
                        "expected_result": test_data_json.get("expected_result", ""),
                        "assertions": assertions,
                        "success": all(a.success for a in assertions)
                    })
            
            # 执行业务级断言（数据一致性）
            consistency_results = self.data_consistency_assertion.assert_condition(business_data)
            
            # 生成业务摘要
            summary = self._generate_business_summary(
                record_id, operation_results, consistency_results, business_data
            )
            
            return summary
            
        except Exception as e:
            logger.error(f"业务断言执行失败 record_id={record_id}: {str(e)}")
            logger.error(traceback.format_exc())
            return {
                "success": False,
                "error": str(e),
                "record_id": record_id
            }
    
    def _generate_business_summary(self, record_id: str, operation_results: List[Dict],
                                 consistency_results: List[AssertionResult],
                                 business_data: List[Dict]) -> Dict[str, Any]:
        """生成业务执行摘要"""
        # 统计断言结果
        total_operations = len(operation_results)
        successful_operations = sum(1 for op in operation_results if op["success"])
        
        total_assertions = sum(len(op["assertions"]) for op in operation_results) + len(consistency_results)
        passed_assertions = sum(
            sum(1 for a in op["assertions"] if a.success) for op in operation_results
        ) + sum(1 for c in consistency_results if c.success)
        
        # 业务是否成功（所有操作都成功）
        business_success = successful_operations == total_operations
        
        # 按操作类型统计
        operation_stats = {}
        for op in operation_results:
            op_type = op["operation_type"]
            if op_type not in operation_stats:
                operation_stats[op_type] = {"total": 0, "success": 0}
            operation_stats[op_type]["total"] += 1
            if op["success"]:
                operation_stats[op_type]["success"] += 1
        
        return {
            "record_id": record_id,
            "business_success": business_success,
            "summary": {
                "total_operations": total_operations,
                "successful_operations": successful_operations,
                "total_assertions": total_assertions,
                "passed_assertions": passed_assertions,
                "success_rate": passed_assertions / total_assertions if total_assertions > 0 else 0
            },
            "operation_stats": operation_stats,
            "operation_results": operation_results,
            "consistency_results": [r.to_dict() for r in consistency_results]
        }
    
    def print_business_results(self, result: Dict[str, Any], detailed: bool = False):
        """打印业务执行结果"""
        if result.get("error"):
            print(f"\n❌ 业务执行失败: {result['error']}")
            return
        
        print(f"\n{'='*80}")
        print(f"📊 业务执行报告 - Record ID: {result['record_id']}")
        print(f"{'='*80}")
        
        # 总体状态
        status_icon = "✅" if result["business_success"] else "❌"
        print(f"\n{status_icon} 业务状态: {'成功' if result['business_success'] else '失败'}")
        
        # 统计信息
        summary = result["summary"]
        print(f"\n📈 执行统计:")
        print(f"   • 总操作数: {summary['total_operations']}")
        print(f"   • 成功操作: {summary['successful_operations']}")
        print(f"   • 总断言数: {summary['total_assertions']}")
        print(f"   • 通过断言: {summary['passed_assertions']}")
        print(f"   • 成功率: {summary['success_rate']:.1%}")
        
        # 操作类型统计
        print(f"\n📋 操作统计:")
        for op_type, stats in result["operation_stats"].items():
            success_rate = stats["success"] / stats["total"] if stats["total"] > 0 else 0
            print(f"   • {op_type}: {stats['success']}/{stats['total']} ({success_rate:.1%})")
        
        # 数据一致性结果
        if result["consistency_results"]:
            print(f"\n🔍 数据一致性检查:")
            for consistency in result["consistency_results"]:
                icon = "✅" if consistency["success"] else "❌"
                print(f"   {icon} {consistency['description']}")
        
        # 详细模式：显示每个操作的断言结果
        if detailed:
            print(f"\n📝 操作详情:")
            for i, op_result in enumerate(result["operation_results"], 1):
                print(f"\n   {i}. {op_result['case_name']} ({op_result['operation_type']})")
                print(f"      描述: {op_result['description']}")
                print(f"      预期: {op_result['expected_result']}")
                print(f"      结果: {'成功' if op_result['success'] else '失败'}")
                
                print(f"      断言结果:")
                for assertion in op_result["assertions"]:
                    icon = "✓" if assertion.success else "✗"
                    print(f"        {icon} {assertion.description}")
                    print(f"           {assertion.message}")
    
    def run_business_assertions(self, limit: int = 10, detailed: bool = False) -> List[Dict[str, Any]]:
        """批量执行业务断言"""
        # 获取最近的record_id
        query = """
        SELECT record_id, MIN(id) as min_id
        FROM test_data
        WHERE record_id IS NOT NULL AND record_id != -1 
        GROUP BY record_id
        ORDER BY min_id DESC
        LIMIT %s
        """
        
        records = self.db_manager.execute_query(query, (limit,))
        
        results = []
        for record in records:
            record_id = record["record_id"]
            print(f"\n正在执行业务 {record_id} 的断言...")
            
            result = self.execute_business_assertions(str(record_id))
            results.append(result)
            
            # 打印结果
            self.print_business_results(result, detailed=detailed)
        
        # 打印总体统计
        self._print_overall_statistics(results)
        
        return results
    
    def export_results_to_json(self, results: List[Dict[str, Any]], filename: str = None) -> str:
        """将断言结果导出为JSON格式（优化为前端友好的结构）"""
        if filename is None:
            filename = f"assertion_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        
        # 准备导出数据
        export_data = {
            "metadata": {
                "execution_time": datetime.now().isoformat(),
                "execution_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "total_businesses": len(results),
                "successful_businesses": sum(1 for r in results if r.get("business_success", False)),
                "failed_businesses": sum(1 for r in results if not r.get("business_success", False) and not r.get("error")),
                "error_businesses": sum(1 for r in results if r.get("error")),
                "business_success_rate": sum(1 for r in results if r.get("business_success", False)) / len(results) * 100 if results else 0
            },
            "summary": {
                "by_status": {
                    "success": sum(1 for r in results if r.get("business_success", False)),
                    "failed": sum(1 for r in results if not r.get("business_success", False) and not r.get("error")),
                    "error": sum(1 for r in results if r.get("error"))
                },
                "by_operation": {},
                "by_assertion": {}
            },
            "businesses": []
        }
        
        # 收集统计数据
        operation_stats = {}
        assertion_stats = {}
        
        # 处理每个业务的结果
        for result in results:
            if result.get("error"):
                # 错误的业务
                business_data = {
                    "record_id": str(result["record_id"]),
                    "status": "error",
                    "status_text": "执行错误",
                    "error_message": result["error"],
                    "summary": {
                        "total_operations": 0,
                        "successful_operations": 0,
                        "total_assertions": 0,
                        "passed_assertions": 0,
                        "success_rate": 0
                    }
                }
            else:
                # 正常的业务结果
                status = "success" if result["business_success"] else "failed"
                status_text = "成功" if result["business_success"] else "失败"
                
                business_data = {
                    "record_id": str(result["record_id"]),
                    "status": status,
                    "status_text": status_text,
                    "summary": {
                        "total_operations": result["summary"]["total_operations"],
                        "successful_operations": result["summary"]["successful_operations"],
                        "total_assertions": result["summary"]["total_assertions"],
                        "passed_assertions": result["summary"]["passed_assertions"],
                        "success_rate": round(result["summary"]["success_rate"] * 100, 1)
                    },
                    "operation_breakdown": [],
                    "operations": []
                }
                
                # 添加操作类型分解
                for op_type, stats in result["operation_stats"].items():
                    business_data["operation_breakdown"].append({
                        "type": op_type,
                        "total": stats["total"],
                        "success": stats["success"],
                        "success_rate": round(stats["success"] / stats["total"] * 100 if stats["total"] > 0 else 0, 1)
                    })
                    
                    # 更新总体统计
                    if op_type not in operation_stats:
                        operation_stats[op_type] = {"total": 0, "success": 0}
                    operation_stats[op_type]["total"] += stats["total"]
                    operation_stats[op_type]["success"] += stats["success"]
                
                # 添加操作详情
                for idx, op_result in enumerate(result["operation_results"]):
                    operation_data = {
                        "index": idx + 1,
                        "operation_type": op_result["operation_type"],
                        "operation_icon": self._get_operation_icon(op_result["operation_type"]),
                        "case_name": op_result["case_name"],
                        "description": op_result["description"],
                        "expected_result": op_result["expected_result"],
                        "success": op_result["success"],
                        "status_text": "通过" if op_result["success"] else "失败",
                        "assertions": []
                    }
                    
                    # 添加断言详情
                    for assertion in op_result["assertions"]:
                        assertion_type = assertion.assertion_type.value
                        
                        # 更新断言统计
                        if assertion_type not in assertion_stats:
                            assertion_stats[assertion_type] = {"total": 0, "passed": 0}
                        assertion_stats[assertion_type]["total"] += 1
                        if assertion.success:
                            assertion_stats[assertion_type]["passed"] += 1
                        
                        assertion_data = {
                            "type": assertion_type,
                            "type_text": self._get_assertion_type_text(assertion_type),
                            "success": assertion.success,
                            "status_icon": "✓" if assertion.success else "✗",
                            "message": assertion.message,
                            "description": assertion.description,
                            "expected": assertion.expected,
                            "actual": assertion.actual
                        }
                        operation_data["assertions"].append(assertion_data)
                    
                    business_data["operations"].append(operation_data)
                
                # 添加数据一致性结果
                if result.get("consistency_results"):
                    business_data["consistency_checks"] = []
                    for check in result["consistency_results"]:
                        business_data["consistency_checks"].append({
                            "type": check["type"],
                            "success": check["success"],
                            "message": check["message"],
                            "description": check["description"]
                        })
            
            export_data["businesses"].append(business_data)
        
        # 更新总体统计
        export_data["summary"]["by_operation"] = {
            op_type: {
                "total": stats["total"],
                "success": stats["success"],
                "success_rate": round(stats["success"] / stats["total"] * 100 if stats["total"] > 0 else 0, 1)
            }
            for op_type, stats in operation_stats.items()
        }
        
        export_data["summary"]["by_assertion"] = {
            assertion_type: {
                "total": stats["total"],
                "passed": stats["passed"],
                "success_rate": round(stats["passed"] / stats["total"] * 100 if stats["total"] > 0 else 0, 1)
            }
            for assertion_type, stats in assertion_stats.items()
        }
        # 确保 data 目录存在
        os.makedirs("data", exist_ok=True)
    
        # 在 filename 前加上 data/ 前缀
        filepath = os.path.join("data", filename)

        # 保存到文件
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(export_data, f, ensure_ascii=False, indent=2, default=str)
        
        print(f"\n✅ 结果已导出到文件: {filepath}")
        
        return filepath
    
    def _get_operation_icon(self, operation_type: str) -> str:
        """获取操作类型的图标"""
        icons = {
            "create": "➕",
            "read": "👁",
            "update": "✏️",
            "delete": "🗑️"
        }
        return icons.get(operation_type, "❓")
    
    def _get_assertion_type_text(self, assertion_type: str) -> str:
        """获取断言类型的中文描述"""
        texts = {
            "status_code": "状态码断言",
            "response_time": "响应时间断言",
            "data_consistency": "数据一致性断言",
            "error_message": "错误信息断言"
        }
        return texts.get(assertion_type, assertion_type)
    
    def _generate_overall_statistics(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:
        """生成总体统计信息"""
        # 操作类型统计
        operation_totals = {}
        for result in results:
            if "operation_stats" in result:
                for op_type, stats in result["operation_stats"].items():
                    if op_type not in operation_totals:
                        operation_totals[op_type] = {"total": 0, "success": 0}
                    operation_totals[op_type]["total"] += stats["total"]
                    operation_totals[op_type]["success"] += stats["success"]
        
        # 断言类型统计
        assertion_stats = {}
        for result in results:
            for op_result in result.get("operation_results", []):
                for assertion in op_result["assertions"]:
                    assertion_type = assertion.assertion_type.value
                    if assertion_type not in assertion_stats:
                        assertion_stats[assertion_type] = {"total": 0, "passed": 0}
                    assertion_stats[assertion_type]["total"] += 1
                    if assertion.success:
                        assertion_stats[assertion_type]["passed"] += 1
        
        # 计算成功率
        for op_type in operation_totals:
            stats = operation_totals[op_type]
            stats["success_rate"] = stats["success"] / stats["total"] if stats["total"] > 0 else 0
        
        for assertion_type in assertion_stats:
            stats = assertion_stats[assertion_type]
            stats["success_rate"] = stats["passed"] / stats["total"] if stats["total"] > 0 else 0
        
        return {
            "operation_statistics": operation_totals,
            "assertion_statistics": assertion_stats
        }
    
    def _print_overall_statistics(self, results: List[Dict[str, Any]]):
        """打印总体统计信息"""
        print(f"\n{'='*80}")
        print(f"📊 总体统计")
        print(f"{'='*80}")
        
        total_businesses = len(results)
        successful_businesses = sum(1 for r in results if r.get("business_success", False))
        
        print(f"\n业务总数: {total_businesses}")
        print(f"成功业务: {successful_businesses}")
        print(f"业务成功率: {successful_businesses/total_businesses:.1%}" if total_businesses > 0 else "0%")
        
        # 操作类型统计
        operation_totals = {}
        for result in results:
            if "operation_stats" in result:
                for op_type, stats in result["operation_stats"].items():
                    if op_type not in operation_totals:
                        operation_totals[op_type] = {"total": 0, "success": 0}
                    operation_totals[op_type]["total"] += stats["total"]
                    operation_totals[op_type]["success"] += stats["success"]
        
        if operation_totals:
            print(f"\n操作类型统计:")
            for op_type, stats in operation_totals.items():
                success_rate = stats["success"] / stats["total"] if stats["total"] > 0 else 0
                print(f"  • {op_type}: {stats['success']}/{stats['total']} ({success_rate:.1%})")
        
        # 断言类型统计
        assertion_stats = {}
        for result in results:
            for op_result in result.get("operation_results", []):
                for assertion in op_result["assertions"]:
                    assertion_type = assertion.assertion_type.value
                    if assertion_type not in assertion_stats:
                        assertion_stats[assertion_type] = {"total": 0, "passed": 0}
                    assertion_stats[assertion_type]["total"] += 1
                    if assertion.success:
                        assertion_stats[assertion_type]["passed"] += 1
        
        if assertion_stats:
            print(f"\n断言类型统计:")
            for assertion_type, stats in assertion_stats.items():
                success_rate = stats["passed"] / stats["total"] if stats["total"] > 0 else 0
                print(f"  • {assertion_type}: {stats['passed']}/{stats['total']} ({success_rate:.1%})")


def main():
    """主函数 - 使用示例"""
    # 数据库配置
    db_config = {
        "host": settings.DB_HOST,
        "user": settings.DB_USER,
        "password": settings.DB_PASSWORD,  # 从环境变量安全获取
        "database": settings.DB_NAME,
        "port": settings.DB_PORT,
    }
    
    try:
        # 创建数据库管理器
        db_manager = DatabaseManager(**db_config)
        db_manager.connect()
        
        # 创建断言引擎
        engine = BusinessAssertionEngine(db_manager)
        
        print("🚀 开始执行业务级自动断言...")
        print("="*80)
        
        # 执行断言（可以选择是否显示详细信息）
        # results = engine.run_business_assertions(limit=5, detailed=False)  # 摘要模式
        results = engine.run_business_assertions(limit=100, detailed=True)  # 详细模式
        
        # 导出结果为JSON
        if results:
            json_file = engine.export_results_to_json(results,"assertion_results.json")
            print(f"\n📄 JSON文件保存路径: {json_file}")
            
            # 也可以指定文件名
            # engine.export_results_to_json(results, "my_test_results.json")
        
        # 示例：执行单个业务的断言
        # record_id = "1837147714514985"
        # result = engine.execute_business_assertions(record_id)
        # engine.print_business_results(result, detailed=True)
        # engine.export_results_to_json([result], f"business_{record_id}_results.json")
        
    except Exception as e:
        print(f"\n❌ 执行失败: {str(e)}")
        traceback.print_exc()
    finally:
        if 'db_manager' in locals():
            db_manager.disconnect()


if __name__ == "__main__":
    main()